/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Eaxmple_01_ArrayList.java]
 * Creation Date        [19-Jun-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_06_collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * 集合框架 java.util.ArrayList
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
@SuppressWarnings("unused")
public class Eaxmple_01_ArrayList {

	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 */
	public static void main(String[] args) {
		// 创建一个ArrayList
		ArrayList<String> list1 = new ArrayList<String>();

		// 创建一个指定大小的ArrayList
		ArrayList<String> list2 = new ArrayList<String>(10);
		// 增加list2的容量
		list2.ensureCapacity(5);
		// list2.set(0, "Wrong set"); 如果ArrayList的size不大于要设置的元素的位置, 不能使用set方法
		list2.add("Hello ");
		list2.add("World ");
		// 去掉多余的空元素
		list2.trimToSize();
		System.out.println("List2's size = " + list2.size());
		// 向ArrayList中间位置添加元素
		list2.add(list2.size() / 2, "New ");
		System.out.println("list2 = " + list2);
		// 转换为数组
		String[] strArray = new String[list2.size()];
		strArray = list2.toArray(strArray);
		System.out.println("String array = " + Arrays.toString(strArray));

		// 遍历 ArrayList 方式1
		for (int i = 0; i < list2.size(); i++) {
			String temp = list2.get(i);// 效率不高
			System.out.print(temp + "\t");
		}
		System.out.println();

		// 遍历ArrayList 方式2
		Iterator<String> iter = list2.iterator();
		while (iter.hasNext()) {
			String temp = iter.next();
			System.out.print(temp + "\t");
		}
		System.out.println();

		// 遍历ArrayList 方式3, 可以正向/反向遍历
		ListIterator<String> iter2 = list2.listIterator();
		while (iter2.hasNext()) {
			String temp = iter2.next();
			System.out.print(temp + "\t");
		}
		System.out.println();
		while (iter2.hasPrevious()) {
			String temp = iter2.previous();
			System.out.print(temp + "\t");
		}
		System.out.println();

	}

}
